package com.mj.screenshot.widget;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import com.mj.screenshot.R;
import com.mj.screenshot.util.DateUtils;
import com.mj.screenshot.util.SDCardUtils;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.View.OnTouchListener;
import android.view.WindowManager.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

public class FloatService extends Service {
	@SuppressWarnings("unused")
	private static final String TAG = FloatService.class.getSimpleName();
	// 定义浮动窗口布局
	private LinearLayout mFloatLayout;
	private WindowManager.LayoutParams wmParams;
	// 创建浮动窗口设置布局参数的对象
	private WindowManager mWindowManager;
	private ImageView mFloatView;
	
	private String filepath; //文件路径
	private static final int SHOTOVER = 1;
	@Override
	public void onCreate() {
		super.onCreate();
		createFloatView();
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@SuppressLint({ "InflateParams", "ClickableViewAccessibility" })
	private void createFloatView() {
		wmParams = new WindowManager.LayoutParams();
		// 获取的是WindowManagerImpl.CompatModeWrapper
		mWindowManager = (WindowManager) getApplication().getSystemService(WINDOW_SERVICE);
		// 设置window type
		wmParams.type = LayoutParams.TYPE_PHONE;
		// 设置图片格式，效果为背景透明
		wmParams.format = PixelFormat.RGBA_8888;
		// 设置浮动窗口不可聚焦（实现操作除浮动窗口外的其他可见窗口的操作）
		wmParams.flags = LayoutParams.FLAG_NOT_FOCUSABLE;
		// 调整悬浮窗显示的停靠位置为左侧置顶
		wmParams.gravity = Gravity.LEFT | Gravity.TOP;
		// 以屏幕左上角为原点，设置x、y初始值，相对于gravity
		wmParams.x = 0;
		wmParams.y = 0;

		// 设置悬浮窗口长宽数据
		wmParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
		wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT;

		/*
		 * // 设置悬浮窗口长宽数据 wmParams.width = 200; wmParams.height = 80;
		 */
		LayoutInflater inflater = LayoutInflater.from(getApplication());
		// 获取浮动窗口视图所在布局
		mFloatLayout = (LinearLayout) inflater.inflate(R.layout.service_float, null);
		// 添加mFloatLayout
		mWindowManager.addView(mFloatLayout, wmParams);
		// 浮动窗口按钮
		mFloatView = (ImageView)mFloatLayout.findViewById(R.id.service_float_imageView);
		mFloatLayout.measure(View.MeasureSpec.makeMeasureSpec(0,
				View.MeasureSpec.UNSPECIFIED), View.MeasureSpec
				.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
		// 设置监听浮动窗口的触摸移动
		mFloatView.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// getRawX是触摸位置相对于屏幕的坐标，getX是相对于按钮的坐标
				wmParams.x = (int) event.getRawX() - mFloatView.getMeasuredWidth() / 2;
				// 减25为状态栏的高度
				wmParams.y = (int) event.getRawY() - mFloatView.getMeasuredHeight() / 2 - 25;
				// 刷新
				mWindowManager.updateViewLayout(mFloatLayout, wmParams);
				screenshot1();
				return false; // 此处必须返回false，否则OnClickListener获取不到监听
//				return true;
			}
		});

		mFloatView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				screenshot1();
			}
		});
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (mFloatLayout != null) {
			// 移除悬浮窗口
			mWindowManager.removeView(mFloatLayout);
		}
	}

	/**
	 *  需要root权限
	 */
	private void screenshot1() {
		filepath = SDCardUtils.getSavePath() +"screenshot_"+DateUtils.format(new Date(), "yyyyMMddHHmmss")+".png";
		String cmd = "su -c screencap -p "+filepath;
		try {
			Runtime.getRuntime().exec(cmd);
		} catch (IOException e) {
			e.printStackTrace();
		}
//		File file = new File(filepath);
//		if (file.exists()) {
//			Toast.makeText(getApplicationContext(), "保存到："+filepath, Toast.LENGTH_SHORT).show();
//		}
		Message msg = new Message();
		msg.what = SHOTOVER;
		handler.sendMessage(msg);
	}
	
	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case SHOTOVER:
				File file = new File(filepath);
				if (file.exists()) {
					Toast.makeText(getApplicationContext(), "保存到："+filepath, Toast.LENGTH_SHORT).show();
				}
				break;

			default:
				break;
			}
		}
	};
}